package lib;

import java.io.Serializable;


/**
 * Parser for a command such as 'CreateUser userName'
 */
public class CommandParser
{
    /**
     * Parses command from given string
     *
     * @param commandString
     * @return parsed command
     */
    public static Command ParseCommand(String commandString)
    {
        ArgumentValidator.IsNotNullOrEmpty("commandString", commandString);

        String tokens[] = SplitCommandIntoTokens(commandString);

        // First token is command, rest all are arguments
        String commandName = tokens[0];

        Serializable commandArgs[] = new Serializable[tokens.length - 1];
        for (int i = 1; i < tokens.length; ++i) 
        {
            commandArgs[i - 1] = tokens[i];
        }

        return new Command(commandName, commandArgs);
    }

    private static String[] SplitCommandIntoTokens(String commandString)
    {
        String delimiterIgnoringMultipleSpaces = "[ ]+";
        return commandString.split(delimiterIgnoringMultipleSpaces);
    }
}
